import { HttpAdapterHost, NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { ConfigService } from '@nestjs/config';
import { WINSTON_MODULE_NEST_PROVIDER } from 'nest-winston';
import { AllExceptionFilter } from './common/filters/all-exception.filter';
import { VERSION_NEUTRAL, VersioningType } from '@nestjs/common';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);

  const configService = app.get(ConfigService);
  const port = configService.get<number>('PORT', 3000);
  const cors = configService.get<boolean>('CORS', false);
  const prefix = configService.get<string>('PREFIX', '/api');
  const version: string | undefined = configService.get<string>('VERSION');
  let versions: string[];
  if (version && version.indexOf(',') !== -1) {
    versions = version.split(',');
  } else {
    versions = version ? [version] : [];
  }

  const errorFilterFlag = configService.get<string>('ERROR_FILTER');

  app.useLogger(app.get(WINSTON_MODULE_NEST_PROVIDER));

  // 全局属性项
  app.setGlobalPrefix(prefix);
  app.enableVersioning({
    type: VersioningType.URI,
    // 如果有版本号，就使用版本号，没有就使用默认版本号，即 VERSION_NEUTRAL
    defaultVersion: typeof versions === 'string' ? versions : VERSION_NEUTRAL,
  });

  if (cors === true) {
    app.enableCors();
  }

  if (errorFilterFlag === 'false') {
    const httpAdapter = app.get(HttpAdapterHost);
    app.useGlobalFilters(new AllExceptionFilter(httpAdapter));
  }

  console.log('Application running on port:', port);
  await app.listen(port);
}
bootstrap();
